package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code40DiameterOfBinaryTree {

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public int diameterOfBinaryTree(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int[] max = new int[1];
        maxDepth(root, max);
        return max[0];
    }

    private int maxDepth(TreeNode node, int[] max) {
        if (node == null) {
            return 0;
        }
        // 分别找当前节点的左右子树的最大深度
        int ld = maxDepth(node.left, max);
        int rd = maxDepth(node.right, max);
        // 收集结果
        max[0] = Math.max(max[0], ld + rd);
        // 当前节点的最大深度
        return Math.max(ld, rd) + 1;
    }
}
